<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\CashCode;
use think\Db;
/**
 * 首页接口
 */
class Index extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     * 
     */
    public function index()
    {
        $this->success('请求成功');
    }
	//查询现金券
	public function cashquery(){
		
		@date_default_timezone_set('America/New_York');
	/* 	 $.post('http://fadmin.uni.com/api/index/cashquery',{email:'lyl@qq.com'},function(res){
			if(res !=''){
			
				var obj = JSON.parse(res);
				obj.forEach(e){
					console.log(e['code']);
				}	
			}
		  }) */
		
		if($this->request->isPost()){
			
			//根据邮箱查询用户现金券
			$email = $this->request->request("email");
			$cart_amount =   $this->request->request("cart_amount");
			
			if(trim($email) == ''){
				
				
				return '[]' ;
			}
			
			$dateformat = $this->request->request("dateformat");
			
			if($cart_amount){
							//未使用 , 未超期 
			$cashcode = CashCode::where('is_use','否')->where('status','normal')->where('email',$email)
			->where('date_end','>=',date('Y-m-d'))->where('group_name','notlike', 'GF%')->where('amount_min' , '<' ,$cart_amount)->select();  
			
				
			}else{
							//未使用 , 未超期 
			$cashcode = CashCode::where('is_use','否')->where('status','normal')->where('email',$email)->
			where('date_end','>=',date('Y-m-d'))->where('group_name','notlike', 'GF%')->select();  
			
				
				
			}
			//自定义 日期格式化
			if($dateformat){
				
				$i=0;
				foreach($cashcode as $item) {
					$cashcode[$i]['date_end']=date($dateformat,strtotime($item['date_end']));
					$i++;
				}	
			}

			return json_encode($cashcode) ;
			
		}
		
		
	}
	
	//兑换现金券
	public function cashexchange(){
		
		/* 	$.post('http://fadmin.uni.com/api/index/cashexchange',{email:'lyl@qq.com',code:'109681e306e6816dc8adc5c8b175d06c'},function(res){
		
		  console.log(res)
		  }) */
		
		if($this->request->isPost()){
			
			$code = $this->request->request("code");
			$email = $this->request->request("email");
			$cashcode = CashCode::get(['code'=>$code]);  
			if($cashcode){
				
				if(strtotime($cashcode->date_end) >= time()){
				
					
					if($cashcode->email !=''){
						
						return   'code is exchanged';
					}else{
						$cashcode->is_exchange = '是';
						$cashcode->email = $email;
						
					}
					
					$cashcode->save();
					return 'ok';
				}else{
					
					return   'code expired';
					
				}
	
			}else{
				
				  return  'code invalid';
				
			}	
		}
	}
	//购物车使用
    //现金券使用规则：
    //1. 现金券 最小使用金额 和最大使用金额 无指定 ， 则购物车可使用最大现金券金额为 出去运费外的最大订单金额
    //2. 现金券 存在最小使用金额 ，则购物车除运费外 最大金额 必须要大于这个金额 才可以正常使用 ，并且最大额度 不超过除运费外最大金额
    //3. 现金券 存在最大最小使用金额， 则购物车除运费外 最大金额 必须要在此区间 才可以正常使用 ，并且最大额度 不超过除运费外最大金额
    //4. 现金券 只可以用于一笔完成交易的订单 
    //5. 未支付订单占用现金券名额 取消后 恢复现金券名额
    //6. 已使用的 现金券 不可以删除  未使用的可以直接删除
	public function cashcart(){
		/* 	$.post('http://fadmin.uni.com/api/index/cashcart',{id_cart:'999',code:'109681e306e6816dc8adc5c8b175d06c'},function(res){
		
		  console.log(res)
		  }) */
		@date_default_timezone_set('America/New_York');
		if($this->request->isPost() || true){
			
			$code = $this->request->request("code");
			$id_cart = $this->request->request("id_cart");
			$cashcode = CashCode::get(['code'=>$code]);  
			$cart_amount = $this->request->request("order_total");
			//获取 购物车当前支付金额  如果 在限制范围区间 则可以使用 
			if($cashcode){
				//检测购物车是否存在清仓产品
				$products =  Db::query("select  a.id_cart,a.id_product,a.id_product_attribute ,b.reference ,b.id_category_default ,c.`name`
										 from  ps_cart_product a  
										LEFT JOIN  ps_product b  on a.id_product  =b.id_product 
										LEFT JOIN  ps_product_lang  c on  b.id_product = c.id_product  and  c.id_lang=1 and c.id_shop=1
										where  a.id_cart  = ".(int)$id_cart);
			
				if($products){
					foreach($products as $a){
						//检测购物车是否存在分类清仓产品 
					    $check_category = Db::query("select id_category from  ps_category_product where id_product = ".(int)$a['id_product'].
						" and id_category = 40456");
						if($check_category){
							die(  'This cash code is not used for Clearance products : '.$a['name']);
						}
						//检测购物车是否存在tag清仓产品 
						$check_tag = Db::query('select id_tag  from  px_tag_extra
												where  `name` like "clearance%"
												and skus  like "%'.$a['reference'].'%"');
						if($check_tag){
							
							die(  'This cash code is not used for Clearance products : '.$a['name']);
						
						}
					}
					
				}
				
				
				$amount = $cashcode->amount;
				$cart_amount =   $cart_amount;
				$amount_min =   $cashcode->amount_min;
				$amount_max =   $cashcode->amount_max;
				
				//无限制
				if($amount_min == 0 && $amount_max ==  0 ){
						
				}

                //存在 最小使用金额  最大使用金额 无限制
                if($amount_min  > 0 &&  $amount_max  == 0  &&  $cart_amount  <  $amount_min  ){
                  
                        die(  'this cash code only used for  more than  Subtotal $' .$amount_min );

                }
					
				//存在 最小使用金额 最大使用金额
                if($amount_min  > 0 &&  $amount_max  > 0    && ( $cart_amount  < $amount_min  ||   $cart_amount  > $amount_max ) ){
                       
                    //    die(  'this cash code only used for subtotal  bewteen $'.$amount_min.'  and  $' . $amount_max);
                    die(  'this cash code only used for subtotal  bewteen $'.$amount_min);
 
                }
				
                //符合所有使用条件 
                //注意 现金券 最大使用金额 不超过 订单subtotal 金额 无法抵扣运费
                if($amount >$cart_amount ){
                    
                    $amount  = $cart_amount ;
                }
				$res = Db::query("INSERT INTO fa_cash_code_cart (`id_cart`,`code`,`amount`,`createtime`)
							VALUES
								('$id_cart','$code','$amount','".time()."')
							ON DUPLICATE KEY UPDATE   code=VALUES(code), amount=VALUES(amount),createtime=VALUES(createtime); ");
						
				die( 'ok');

					
			
			
			}else{
				
				die( 'invalid code');
				
			}
		
			
		}
	}
	
	//页面刷新 清空当前购物车现金券记录
	public function  cashclear(){
		
		/* 	$.post('http://fadmin.uni.com/api/index/cashclear',{id_cart:'999'},function(res){
		
		  console.log(res)
		  }) */
		
		if($this->request->isPost()){
			
			
			$id_cart = $this->request->request("id_cart");
			//如果只有一个记录 不予删除
			$res = Db::query("DELETE FROM `fa_cash_code_cart` WHERE (`id_cart`='$id_cart') ");
			//echo "DELETE FROM `fa_cash_code_cart` WHERE (`id_cart`='$id_cart') ";
			die('ok');
		}
			
	}
	
	
	
	//查询订单 购物车 现金券 金额
	public function  querycart(){
		
		/* 	$.post('http://fadmin.uni.com/api/index/querycart',{id_cart:'999'},function(res){
		
		  console.log(res)
		  }) */
		
		if($this->request->isPost()){
			
			
			$id_cart = $this->request->request("id_cart");
			
			$res = Db::query("select amount FROM `fa_cash_code_cart` WHERE (`id_cart`='$id_cart') ");
			
			if($res){
				
				return $res['0']['amount'];
			}else{
				
				
				return  0;
			}
			
				
		}
			
	}
	
	//创建订单后 要更新现金券使用状态
	public function cashorder(){
		if($this->request->isPost()){
			$code = $this->request->request("code");
			
			$cashcode = CashCode::get(['code' => $code]);
			$cashcode->is_use = '是';
			$cashcode->save();
			return 'ok';
		
		}
       
	}
	
	//批量领取
	public function getCashs(){
		
		$email = $this->request->request("email");	
		$codes = $this->request->request("codes");
		$lists = [];
		/* foreach(){
			
			
			$lists = $this->getCash(true);
		} */
		
		
	}
	
	
	//创建一张指定客户的现金券  
	
	
	public function getCash($internel =false ){
		
		if(false){
			$test = true;
			$_REQUEST['email']='lyl@uniwigs.com';
			$_REQUEST['code']='HappyAnniversary';
			
		}else{
			
			$test = false;
		}

		if($this->request->isPost() ||  $internel  || $test ){
			$email = $this->request->request("email");
			
			$code = $this->request->request("code");
            $mouthFirstDay=date('Y-m-01', strtotime(date("Y-m-d")));
			//当月最后一天
            $mouthLastDay  =  date('Y-m-d', strtotime("$mouthFirstDay +1 month -1 day"));
			
			
			if($email == ''  or  $code == ''){
				$this->json_error( 'params lost!' ,310001 );	
			}
			
			//大于10位的可能为 md5编码code 
			if(strlen($code) >10 ){
				$sql = "select  REPLACE(group_name,'tpl-','') as `code` ,  
				MD5(REPLACE(group_name,'tpl-',''))  from  fa_cash_code 
						where  1 
						and  group_name like 'tpl-%' 
						and  MD5(REPLACE(group_name,'tpl-',''))  =  '".$code."'";
			   $res = Db::query($sql);
			   if($res){
				   $code  =  $res['0']['code'];
			   }
				
			}
			
			//暂时屏蔽自动领取入口
			$auto_code_lists =  [ 'HappyBirthdayMonth','HappyAnniversary' ,'Happy10thAnniversary' 
			,'SeptemberVIP','Secondordervoucher','Septemberloyaltycustomer' ,'2022loyaltycustomerrewards' ];
			$auto_get = false ;
			if(in_array($code, $auto_code_lists)){
				if($this->checkCustomerCashRules($code,$email)){	
					$auto_get =true ;
				}
				
				
				if(!$auto_get){

					$this->json_error( 'invalid code!' ,310002 );	
				}

			}
			
			//开始领取 
			$cashcode =new CashCode();
			$cashcode->code = md5(uniqid() . time());
			
			
			

			//检测是否 已经领取过 同类型的现金券
			//如果是 老客户和生日券 则检测当月是否领取
            if($code == 'birthday' ||  $code  == 'old'){
                
                 $res = Db::query("select amount FROM `fa_cash_code` WHERE `description`='$code'  
			and  `email` =  '$email'  and date_end = '".$mouthLastDay ."'"); 
                
            }else{
                
               $res = Db::query("select amount FROM `fa_cash_code` WHERE `description`='$code'  
			and  `email` =  '$email' "); 
                
            }
			
			//所有类型现金券 默认只能领取一次  	且不是自动领取的折扣券
			//检测邮件是否 已经存在一张同类型的现金券
			if($res && !$auto_get){  
				$this->json_error( 'you have got this code!' ,310003 );  
			}
			
			$cashtpl = CashCode::get(['group_name' => 'tpl-'.$code]);
			//折扣券模板 不存在
			if(!$cashtpl){  
				$this->json_error( 'invalid code!' ,310004 );  	
			}
			//关闭的折扣券 不可以领取 
			if($cashtpl->status == 'deleted'){
				$this->json_error( 'invalid code!' ,310005 );  	
				
			}
			
			
			
			
			
			//自定义有效时间段  标准格式 1:year  day  hour  month week 
			if(trim($cashtpl->valid_date) != ''){
				$valid_rules = explode(':',trim($cashtpl->valid_date));
			
				// day也可以改成year(年)，month(月)，hour(小时)minute(分)，second
				if(count($valid_rules) == 2){
					$number =  (int)($valid_rules[0]);
					$unit =  trim($valid_rules[1]);
					$units =  ['day','month','hour','minute','second','year'];
					if(in_array( $unit ,$units)){
						
						 $cashcode->date_end = date('Y-m-d H:i:s',strtotime('+'.$number.' '.$unit));
					}
					
				}
				
			}
			
			//未指定有效时间段 valid_date 则已模板现金券的失效日期为准
			if(trim($cashtpl->valid_date)  == ''){
               $cashcode->date_end =  $cashtpl->date_end;//以现金券 模板的 截至日期为准
			}
			
            if($code == 'birthday' ||  $code  == 'old'){
               //生日券 和 老客户 两月未购买券  需要验证签名
               $api_key =  'daskjjlldsajlkdsa1921090210219';
               $month = date("m");
  
               $server_key =  md5(  $code  .   $month . $email . true  .$api_key  ) ;
                
               if($this->request->request("key")  !=  $server_key    ){
                 die('invalid request token');
               }

               $cashcode->date_end =  $mouthLastDay;//有效期 当月有效
               
            }
			
			//专用 30天有效期 
			if('tpl-'.$code == 'tpl-$10TextGiftVoucher'){
				$cashcode->date_end =  $this->getValidDate('30:day');
			}
			
			//生日现金券 20美金 领取开始到月底
			if('tpl-'.$code == 'tpl-HappyBirthdayMonth'){

				$cashcode->date_end = $this->getValidDate('monthLastDay');//重置为当月月底有效
			}
			
			//老客户领取 每月15号 月底到期
			if($code == '2022loyaltycustomerrewards'){
			
				$cashcode->date_end = $this->getValidDate('monthLastDay');//重置为当月月底有效
			
			}
			
		
			
			
			$cashcode->email  = $email ; //使用者
			$cashcode->is_exchange =  '是';
			$cashcode->group_name = (int)$cashtpl->amount .  '$';//现金券名称
			$cashcode->description =  $code;
			$cashcode->amount  = $cashtpl->amount ;//金额
			$cashcode->amount_min  = $cashtpl->amount_min;//最低使用金额
			$cashcode->amount_max  = $cashtpl->amount_max;//最低使用金额
			$cashcode->status  = $cashtpl->status;
			
			$cashcode->save();	
			
			if($internel){
				
				return  ['status'=>'Y','msg'=>'cash code get success','data'=>['code'=>$_POST['code']]];
			}
			
			$this->json_success('cash code get success');
		
		}
		
		
	}
	
	//获取计算现金券 折扣券有效截至日期
	public function getValidDate($format){
		$valid_date = '';
		if(trim($format) != ''){
			$valid_rules = explode(':',trim($format));
		
			// day也可以改成year(年)，month(月)，hour(小时)minute(分)，second
			if(count($valid_rules) == 2){
				$number =  (int)($valid_rules[0]);
				$unit =  trim($valid_rules[1]);
				$units =  ['day','month','hour','minute','second','year'];
				if(in_array( $unit ,$units)){
					
					 $valid_date = date('Y-m-d H:i:s',strtotime('+'.$number.' '.$unit));
				}
				
			}else{
				
				if($format == 'monthLastDay'){
					
					$nowDay = date('Y-m-d');
					$firstDay = date('Y-m-01', strtotime($nowDay));
					$lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
					$valid_date = $lastDay;
				}
				
			}
			
		}
		return  $valid_date;
	
		
	}
	
	
	public function checkCustomerCashRules($type,$email){
		$customer = Db::query("select * FROM `ps_customer` WHERE  `email` =  '$email' limit 0,1 "); 
		
		if(!$customer){
	
			$this->json_error( 'invalid customer!' ,300001 );
				
		}
		$customer = $customer[0];
		
		//检查老客户自动领取 每月15号 触发 每月领一次 
		if($type == '2022loyaltycustomerrewards'){
			
			//1. 15号以及15号以后可以领取
			if(date('d') < '15' ){
				
				$this->json_error( 'invalid time for  get code!' ,300001 );
			}
			
			//检测是否为老客户
			$sql = 'select count(id_order) as number
			from ps_orders where  total_paid_real > 0  and valid=1 and id_customer=' .$customer['id_customer'];
			$res = Db::query($sql);
			$onum = $res ? $res[0]['number'] :0;
			//2. 有效购买次数大于等于2
			if($onum < 2){
				
				$this->json_error( 'code is only for old customer!' ,300001 );
			}
			
			//3. 每月领取一次
			if($this->checkTimes($type ,$email  ,'month')){
				$this->json_error( 'one month you can only  get once for this code!' ,300042 );
			}
			
			
			return true;
		}
		
		
		//检测是否当月生日 
		#HappyBirthdayMonth ：每月的1号触发给当月的所有过生日客户，然后券的有效期是当月最后一天，
		if($type == 'HappyBirthdayMonth'){
			//当前月为客户生日所在月份
			if(strpos($customer['birthday'], date('-m-')) === false){

				$this->json_error( 'just in your birthday  month   get once for this code!' ,300041 );
				
			}	

			//检测当年是否领取过 一年 只能领取一张 且一次 
			if($this->checkTimes($type ,$email  ,'year')){
				
				$this->json_error( 'one year you can only  get once for this code!' ,300043 );
			}
			
			return true ;
		}
		
		# ：注册时间1-9周年当天触发 
		if($type == 'HappyAnniversary'){
			//判断当天为 注册时间的当天
			if(strpos($customer['date_add'], date('-m-d')) === false){
				$this->json_error( 'invalid time for  get once for  this code!' ,300031 );
			}
			//判断年数 在1-9之内  
			$res = Db::query("select TIMESTAMPDIFF(YEAR, '".$customer['date_add']."', '".date('Y-m-d H:i:s')."') as ydiff");
			if(isset($res[0]['ydiff'])){
				
				$year_diff = (int)$res[0]['ydiff'];
			}else{
				
				$year_diff = 0;
			}
			if($year_diff < 1 or  $year_diff >9){

				$this->json_error( 'invalid time for  get code!' ,300032 );
			}
			//当年仅可领取一次 
			if($this->checkTimes($type ,$email  ,'year')){
				
				$this->json_error('one year you can only get once for this code!'  ,300033 );
			}
			
			return true;
	
		}
		
		# Happy10thAnniversary 注册日期的10周年当天触发
		if($type == 'Happy10thAnniversary'){
			//判断当天为 注册周年计时天数 
			if(strpos($customer['date_add'], date('-m-d')) === false){
				$this->json_error( 'invalid time for  get this code!' ,300021 );
			}
			//判断年数 大于等于10
			$year_diff =  date('Y')*1 -  date( 'Y' ,strtotime($customer['date_add']))*1;
			if($year_diff < 10){
				$this->json_error( 'invalid time for  get this code!' ,300022 );
			}
			//当年仅可领取一次 
			if($this->checkTimes($type ,$email  ,'year')){
			
				$this->json_error( 'one year you can only get one code!' ,300023 );
			}
			
			return true;
	
		}
		
		# 取消 Septemberloyaltycustomer 这个早过去了， 是9月份送给老客户的优惠券，15美金 
		# 取消 SeptemberVIP 也是9月分送给老客户的优惠券， 20美金	
		
		#Secondordervoucher  ，首单客户独享的二次订单优惠券， 再发运的邮件下面领取。
		if($type ==  'Secondordervoucher'){
			//又且只有一次订单记录的客户
			$sql = "select count(id_order) as number  from  ps_orders  a
						LEFT JOIN  ps_customer b on a.id_customer =  b.id_customer 
						where  b.email ='".$email."'  
						GROUP BY b.id_customer ; ";
			$check_order = Db::query($sql);
			if(!$check_order){
				
				$this->json_error( 'please  order first!' ,300011 );
			}
			if($check_order[0]['number']  != 1){

				$this->json_error( 'this code is only for have first order customer!'  ,300012);
			}
			
			//只能领取一次  
			if($this->checkTimes($type ,$email  ,'all')){
				$this->json_error( 'you have get this code!' ,300013 );
			}
			return true ;
		}	
				
		
		return false;
	}
	
	public function json_success( $msg){
		
		header('Content-Type:application/json; charset=utf-8');
		$data['status'] = 'Y';
		$data['msg'] = $msg;
		die(json_encode($data));
	}
	
	public function json_error( $msg ,$err_code =0 ){
		
		header('Content-Type:application/json; charset=utf-8');
		$data['status'] = 'N';
		$data['msg'] = $msg;
		$data['err_code'] = $err_code ;
		die(json_encode($data));
	}
	
	//检查 指定客户 指定类型折扣券 领取次数 all year  day  month 
	public function checkTimes($type ,$email  ,$time_type){
		
		if($time_type == 'year'){
			
			$sql = "select id_code ,  FROM_UNIXTIME(createtime,'%Y')
				FROM `fa_cash_code` 
				WHERE `description`='".$type."'
							and  `email` = '".$email."' 
				and FROM_UNIXTIME(createtime,'%Y') = '".date('Y')."'" ;
			$check_repeat = Db::query($sql);

			return count($check_repeat);
		}
		
		if($time_type == 'day'){
			
			$sql = "select id_code ,  FROM_UNIXTIME(createtime,'%Y')
				FROM `fa_cash_code` 
				WHERE `description`='".$type."'
							and  `email` = '".$email."' 
				and FROM_UNIXTIME(createtime,'%d') = '".date('d')."'" ;
			$check_repeat = Db::query($sql);

			return count($check_repeat);
		}
		
		
		if($time_type == 'month'){
			
			$sql = "select id_code ,  FROM_UNIXTIME(createtime,'%Y')
				FROM `fa_cash_code` 
				WHERE `description`='".$type."'
							and  `email` = '".$email."' 
				and FROM_UNIXTIME(createtime,'%m') = '".date('m')."'" ;
			$check_repeat = Db::query($sql);

			return count($check_repeat);
		}
		
		
		//只能领取一次  
		if($time_type == 'all'){
			
			$sql = "select id_code ,  FROM_UNIXTIME(createtime,'%Y')
				FROM `fa_cash_code` 
				WHERE `description`='".$type."'
							and  `email` = '".$email."' " ;
			$check_repeat = Db::query($sql);

			return count($check_repeat);
		}
		
		
	}
	
	
}
